load("@aspect_bazel_lib//lib:copy_to_directory.bzl", "copy_to_directory")
load("@rules_pkg//:pkg.bzl", "pkg_tar")
load("@rules_pkg//pkg:mappings.bzl", "pkg_attributes", "pkg_files", "strip_prefix")
load("//bazel/mkosi:mkosi_image.bzl", "mkosi_image")

copy_to_directory(
    name = "rpms_lts",
    srcs = [
        "@kernel_core_lts//file",
        "@kernel_lts//file",
        "@kernel_modules_core_lts//file",
        "@kernel_modules_lts//file",
    ],
    include_external_repositories = ["kernel*lts"],
    replace_prefixes = {"file": ""},
)

copy_to_directory(
    name = "rpms_mainline",
    srcs = [
        "@kernel_core_mainline//file",
        "@kernel_mainline//file",
        "@kernel_modules_core_mainline//file",
        "@kernel_modules_mainline//file",
    ],
    include_external_repositories = ["kernel*mainline"],
    replace_prefixes = {"file": ""},
)

[
    mkosi_image(
        name = "base_" + kernel_variant,
        srcs = [
            "mkosi.finalize",
            "mkosi.postinst",
            "mkosi.prepare",
        ],
        outs = [
            kernel_variant,
            kernel_variant + ".tar",
            kernel_variant + "-.rpm.lock",
            kernel_variant + "-packagemanifest",
            kernel_variant + "-rpmdb.sqlite",
            kernel_variant + "-rpmdb.sqlite-shm",
            kernel_variant + "-rpmdb.sqlite-wal",
        ],
        extra_trees = [
            ":skeleton",
            "//image:sysroot_tar",
            "//image:cryptsetup_closure",
        ],
        local_mirror = ["@mkosi_rpms//:repo"],
        mkosi_conf = "mkosi.conf",
        output = kernel_variant,
        package_directories = [
            ":rpms_" + kernel_variant,
        ],
        tags = [
            "manual",
            "no-cache",
        ],
        visibility = ["//visibility:public"],
    )
    for kernel_variant in [
        "lts",
        "mainline",
    ]
]

pkg_tar(
    name = "rpmdb",
    srcs = [
        "lts-.rpm.lock",
        "lts-packagemanifest",
        "lts-rpmdb.sqlite",
        "lts-rpmdb.sqlite-shm",
        "lts-rpmdb.sqlite-wal",
    ],
    remap_paths = {
        "/lts-.rpm.lock": "/var/lib/rpm/.rpm.lock",
        "/lts-packagemanifest": "/usr/share/constellation/packagemanifest",
        "/lts-rpmdb.sqlite": "/var/lib/rpm/rpmdb.sqlite",
        "/lts-rpmdb.sqlite-shm": "/var/lib/rpm/rpmdb.sqlite-shm",
        "/lts-rpmdb.sqlite-wal": "/var/lib/rpm/image-rpmdb.sqlite-wal",
    },
    tags = ["manual"],
    visibility = ["//visibility:public"],
)

pkg_files(
    name = "skeleton_files",
    srcs = glob(["mkosi.skeleton/**"]),
    attributes = pkg_attributes(mode = "0555"),
    strip_prefix = strip_prefix.from_pkg("mkosi.skeleton"),
)

pkg_tar(
    name = "skeleton",
    srcs = [":skeleton_files"],
)
